package com.lanbu.web.controller.system;

import com.lanbu.system.domain.PptContext;

import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGradientFillProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGradientStop;
import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor;
import org.openxmlformats.schemas.presentationml.x2006.main.CTBackground;
import org.openxmlformats.schemas.presentationml.x2006.main.CTBackgroundProperties;
import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData;
import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;

@RestController
@RequestMapping("/system/count")
public class pptController {


    @PostMapping("/list")
    public ResponseEntity<String> list(@RequestBody PptContext pptContext, HttpServletRequest request) {
    try {
        String content = pptContext.getContent();

        // 创建 Word 文档
        XWPFDocument doc = new XWPFDocument();
        for (String line : content.split("\n")) {
            line = line.trim();
            if (line.isEmpty()) continue;

            XWPFParagraph paragraph = doc.createParagraph();
            XWPFRun run = paragraph.createRun();

            if (line.startsWith("###")) {
                paragraph.setStyle("Heading3");
                run.setBold(true);
                run.setFontSize(14);
                run.setText(line.replaceFirst("^###\\s*", ""));
            } else if (line.startsWith("-")) {
                paragraph.setStyle("ListBullet");
                run.setText("• " + line.replaceFirst("^-\\s*", ""));
                run.setFontSize(12);
            } else {
                run.setText(line);
                run.setFontSize(12);
            }
        }

        // 保存到临时目录
        String fileName = "word的生成-" + System.currentTimeMillis() + ".docx";
        String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

        try (FileOutputStream out = new FileOutputStream(filePath)) {
            doc.write(out);
        }
        doc.close();

        // 构造可下载链接（根据你实际部署的路径配置）
        String downloadUrl = request.getScheme() + "://" + request.getServerName() +
                ":" + request.getServerPort() + "/system/count/download/" + URLEncoder.encode(fileName, "UTF-8");
        System.out.println(downloadUrl);
        return ResponseEntity.ok(downloadUrl);

    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating document");
    }
}
    @GetMapping("/download/{fileName}")
    public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            String fullPath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
            File file = new File(fullPath);

            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {

                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("Error downloading document");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


//
//
//@PostMapping("/pptlist")
//public ResponseEntity<String> pptlist(@RequestBody PptContext pptContext, HttpServletRequest request) {
//    try {
//        String content = pptContext.getContent();
//        String[] lines = content.split("\n");
//        InputStream templateInputStream = new FileInputStream("mo.pptx");
//        XMLSlideShow ppt = new XMLSlideShow(templateInputStream);
//     //   XMLSlideShow ppt = new XMLSlideShow();
//        XSLFSlide slide = null;
//        XSLFTextShape contentBox = null;
//        int slideIndex = 0;
//
//        for (String line : lines) {
//            line = line.trim();
//            if (line.isEmpty()) continue;
//
//            // 标题行
//            if (line.startsWith("###")) {
//                slide = ppt.createSlide();
//                slide.getBackground().setFillColor(new Color(250, 250, 250));
//                slideIndex++;
//
//                String titleText = line.replaceFirst("^###\\s*", "");
//                XSLFTextShape title = slide.createTextBox();
//                title.setAnchor(new Rectangle(50, 30, 620, 60));
//                XSLFTextParagraph titlePara = title.addNewTextParagraph();
//                titlePara.setTextAlign(TextAlign.CENTER);
//                XSLFTextRun titleRun = titlePara.addNewTextRun();
//                titleRun.setText(titleText);
//                titleRun.setFontSize(28.0);
//                titleRun.setBold(true);
//                titleRun.setFontFamily("微软雅黑");
//
//                contentBox = slide.createTextBox();
//                contentBox.setAnchor(new Rectangle(60, 100, 600, 400));
//
//                XSLFTextShape pageNumber = slide.createTextBox();
//                pageNumber.setAnchor(new Rectangle(680, 500, 100, 30));
//                XSLFTextParagraph pagePara = pageNumber.addNewTextParagraph();
//                pagePara.setTextAlign(TextAlign.RIGHT);
//                XSLFTextRun pageRun = pagePara.addNewTextRun();
//                pageRun.setText("第 " + slideIndex + " 页");
//                pageRun.setFontSize(12.0);
//                pageRun.setFontFamily("微软雅黑");
//            }
//            // 普通内容行
//            else {
//                // 如果还没有创建任何幻灯片，创建默认页
//                if (slide == null) {
//                    slide = ppt.createSlide();
//                    slide.getBackground().setFillColor(new Color(250, 250, 250));
//                    slideIndex++;
//
//                    // 默认标题
//                    XSLFTextShape title = slide.createTextBox();
//                    title.setAnchor(new Rectangle(50, 30, 620, 60));
//                    XSLFTextParagraph titlePara = title.addNewTextParagraph();
//                    titlePara.setTextAlign(TextAlign.CENTER);
//                    XSLFTextRun titleRun = titlePara.addNewTextRun();
//                    titleRun.setText("默认标题");
//                    titleRun.setFontSize(28.0);
//                    titleRun.setBold(true);
//                    titleRun.setFontFamily("微软雅黑");
//
//                    contentBox = slide.createTextBox();
//                    contentBox.setAnchor(new Rectangle(60, 100, 600, 400));
//
//                    XSLFTextShape pageNumber = slide.createTextBox();
//                    pageNumber.setAnchor(new Rectangle(680, 500, 100, 30));
//                    XSLFTextParagraph pagePara = pageNumber.addNewTextParagraph();
//                    pagePara.setTextAlign(TextAlign.RIGHT);
//                    XSLFTextRun pageRun = pagePara.addNewTextRun();
//                    pageRun.setText("第 " + slideIndex + " 页");
//                    pageRun.setFontSize(12.0);
//                    pageRun.setFontFamily("微软雅黑");
//                }
//
//                XSLFTextParagraph para = contentBox.addNewTextParagraph();
//                para.setLineSpacing(120.0);
//
//                if (line.startsWith("-")) {
//                    para.setBullet(true);
//                    line = line.replaceFirst("^-\\s*", "");
//                }
//
//                para.setTextAlign(TextAlign.LEFT);
//
//                Pattern pattern = Pattern.compile("\\*\\*(.*?)\\*\\*");
//                Matcher matcher = pattern.matcher(line);
//                int lastIndex = 0;
//
//                while (matcher.find()) {
//                    if (matcher.start() > lastIndex) {
//                        String normalText = line.substring(lastIndex, matcher.start());
//                        XSLFTextRun run = para.addNewTextRun();
//                        run.setText(normalText);
//                        run.setFontSize(18.0);
//                        run.setFontFamily("微软雅黑");
//                    }
//
//                    String boldText = matcher.group(1);
//                    XSLFTextRun boldRun = para.addNewTextRun();
//                    boldRun.setText(boldText);
//                    boldRun.setFontSize(20.0);
//                    boldRun.setBold(true);
//                    boldRun.setFontFamily("微软雅黑");
//
//                    lastIndex = matcher.end();
//                }
//
//                if (lastIndex < line.length()) {
//                    String remaining = line.substring(lastIndex);
//                    XSLFTextRun run = para.addNewTextRun();
//                    run.setText(remaining);
//                    run.setFontSize(18.0);
//                    run.setFontFamily("微软雅黑");
//                }
//            }
//        }
//
//        String fileName = "ppt的生成-" + System.currentTimeMillis() + ".pptx";
//        String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
//
//        try (FileOutputStream out = new FileOutputStream(filePath)) {
//            ppt.write(out);
//        }
//        ppt.close();
//
//        String downloadUrl = request.getScheme() + "://" + request.getServerName() +
//                ":" + request.getServerPort() + "/system/count/pptdownload/" + URLEncoder.encode(fileName, "UTF-8");
//        return ResponseEntity.ok(downloadUrl);
//
//    } catch (Exception e) {
//        e.printStackTrace();
//        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating PPT");
//    }
//}

    @PostMapping("/pptlist")
    public ResponseEntity<String> pptlist(@RequestBody PptContext pptContext, HttpServletRequest request) {
        try {
            String content = pptContext.getContent();
            String[] lines = content.split("\n");

            // 读取模板
         //   InputStream templateInputStream = new FileInputStream("mo.pptx");
            // 改成这样：
            InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream("mo.pptx");
            if (templateInputStream == null) {
                throw new FileNotFoundException("资源文件 mo.pptx 不存在！");
            }

            XMLSlideShow templatePpt = new XMLSlideShow(templateInputStream);
            XSLFSlide templateSlide = templatePpt.getSlides().get(0); // 取第一张幻灯片作为模板

            // 新建 PPT
            XMLSlideShow newPpt = new XMLSlideShow();
            XSLFSlide currentSlide = null;
            XSLFTextShape contentBox = null;
            int slideIndex = 0;

            for (String line : lines) {
                line = line.trim();
                if (line.isEmpty()) continue;

                if (line.startsWith("###")) {
                    // 新建一页，复制模板页（仅样式）
                    currentSlide = newPpt.createSlide();
                    copySlideLayout(templateSlide, currentSlide);
                    setSolidLightBlueBackground(currentSlide);

                    slideIndex++;
                    String titleText = line.replaceFirst("^###\\s*", "");

                    // 创建标题
                    XSLFTextBox title = currentSlide.createTextBox();
                    title.setAnchor(new Rectangle(50, 30, 620, 60));
                    XSLFTextParagraph titlePara = title.addNewTextParagraph();
                    titlePara.setTextAlign(TextAlign.CENTER);
                    XSLFTextRun titleRun = titlePara.addNewTextRun();
                    titleRun.setText(titleText);
                    titleRun.setFontSize(28.0);
                    titleRun.setBold(true);
                    titleRun.setFontFamily("微软雅黑");

                    // 内容区域
                    contentBox = currentSlide.createTextBox();
                    contentBox.setAnchor(new Rectangle(60, 100, 600, 400));

                    // 页码
                    XSLFTextBox pageNumber = currentSlide.createTextBox();
                    pageNumber.setAnchor(new Rectangle(680, 500, 100, 30));
                    XSLFTextParagraph pagePara = pageNumber.addNewTextParagraph();
                    pagePara.setTextAlign(TextAlign.RIGHT);
                    XSLFTextRun pageRun = pagePara.addNewTextRun();
                    pageRun.setText("第 " + slideIndex + " 页");
                    pageRun.setFontSize(12.0);
                    pageRun.setFontFamily("微软雅黑");
                } else {
                    if (currentSlide == null) {
                        currentSlide = newPpt.createSlide();
                        copySlideLayout(templateSlide, currentSlide);
                        setSolidLightBlueBackground(currentSlide);
                        slideIndex++;

                        // 默认标题
                        XSLFTextBox title = currentSlide.createTextBox();
                        title.setAnchor(new Rectangle(50, 30, 620, 60));
                        XSLFTextParagraph titlePara = title.addNewTextParagraph();
                        titlePara.setTextAlign(TextAlign.CENTER);
                        XSLFTextRun titleRun = titlePara.addNewTextRun();
                        titleRun.setText("默认标题");
                        titleRun.setFontSize(28.0);
                        titleRun.setBold(true);
                        titleRun.setFontFamily("微软雅黑");

                        contentBox = currentSlide.createTextBox();
                        contentBox.setAnchor(new Rectangle(60, 100, 600, 400));

                        XSLFTextBox pageNumber = currentSlide.createTextBox();
                        pageNumber.setAnchor(new Rectangle(680, 500, 100, 30));
                        XSLFTextParagraph pagePara = pageNumber.addNewTextParagraph();
                        pagePara.setTextAlign(TextAlign.RIGHT);
                        XSLFTextRun pageRun = pagePara.addNewTextRun();
                        pageRun.setText("第 " + slideIndex + " 页");
                        pageRun.setFontSize(12.0);
                        pageRun.setFontFamily("微软雅黑");
                    }

                    XSLFTextParagraph para = contentBox.addNewTextParagraph();
                    para.setLineSpacing(120.0);

                    if (line.startsWith("-")) {
                        para.setBullet(true);
                        line = line.replaceFirst("^-\\s*", "");
                    }

                    para.setTextAlign(TextAlign.LEFT);

                    Pattern pattern = Pattern.compile("\\*\\*(.*?)\\*\\*");
                    Matcher matcher = pattern.matcher(line);
                    int lastIndex = 0;

                    while (matcher.find()) {
                        if (matcher.start() > lastIndex) {
                            String normalText = line.substring(lastIndex, matcher.start());
                            XSLFTextRun run = para.addNewTextRun();
                            run.setText(normalText);
                            run.setFontSize(18.0);
                            run.setFontFamily("微软雅黑");
                        }

                        String boldText = matcher.group(1);
                        XSLFTextRun boldRun = para.addNewTextRun();
                        boldRun.setText(boldText);
                        boldRun.setFontSize(20.0);
                        boldRun.setBold(true);
                        boldRun.setFontFamily("微软雅黑");

                        lastIndex = matcher.end();
                    }

                    if (lastIndex < line.length()) {
                        String remaining = line.substring(lastIndex);
                        XSLFTextRun run = para.addNewTextRun();
                        run.setText(remaining);
                        run.setFontSize(18.0);
                        run.setFontFamily("微软雅黑");
                    }
                }
            }

            // 导出文件
            String fileName = "ppt的生成-" + System.currentTimeMillis() + ".pptx";
            String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

            try (FileOutputStream out = new FileOutputStream(filePath)) {
                newPpt.write(out);
            }
            newPpt.close();
            templatePpt.close();

            String downloadUrl = request.getScheme() + "://" + request.getServerName() +
                    ":" + request.getServerPort() + "/system/count/pptdownload/" + URLEncoder.encode(fileName, "UTF-8");
            return ResponseEntity.ok(downloadUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating PPT");
        }
    }

    /**
     * 复制模板幻灯片的布局（样式），不复制文字内容
     */
    private void copySlideLayout(XSLFSlide source, XSLFSlide target) {
        target.getBackground().setFillColor(source.getBackground().getFillColor());

        for (XSLFShape shape : source.getShapes()) {
            if (shape instanceof XSLFTextShape) {
                XSLFTextShape srcTextShape = (XSLFTextShape) shape;
                XSLFTextBox newShape = target.createTextBox();
                newShape.setAnchor(srcTextShape.getAnchor());

                for (XSLFTextParagraph srcPara : srcTextShape.getTextParagraphs()) {
                    XSLFTextParagraph newPara = newShape.addNewTextParagraph();
                    newPara.setTextAlign(srcPara.getTextAlign());
                    newPara.setLineSpacing(srcPara.getLineSpacing());

                    for (XSLFTextRun srcRun : srcPara.getTextRuns()) {
                        XSLFTextRun newRun = newPara.addNewTextRun();
                        newRun.setText(""); // 不复制文字
                        newRun.setFontSize(srcRun.getFontSize());
                        newRun.setFontFamily(srcRun.getFontFamily());
                        newRun.setBold(srcRun.isBold());
                        newRun.setItalic(srcRun.isItalic());
                        newRun.setUnderlined(srcRun.isUnderlined());
                        newRun.setFontColor(srcRun.getFontColor());
                    }
                }
            }
            // 如果还有其他形状（图片、图表等）可以按需复制
        }
    }
//    private void setGradientBlueBackground(XSLFSlide slide) {
//        CTSlide ctSlide = slide.getXmlObject();
//        CTCommonSlideData cSld = ctSlide.getCSld();
//
//        CTBackground bg = cSld.isSetBg() ? cSld.getBg() : cSld.addNewBg();
//        CTBackgroundProperties bgPr = bg.isSetBgPr() ? bg.getBgPr() : bg.addNewBgPr();
//
//        CTGradientFillProperties gradFill = bgPr.addNewGradFill();
//        gradFill.addNewLin().setAng(16200000); // 270°
//
//        CTGradientStop stop1 = gradFill.addNewGsLst().addNewGs();
//        stop1.setPos(0);
//        stop1.addNewSrgbClr().setVal(new byte[]{(byte)173, (byte)216, (byte)230}); // 浅蓝
//
//        CTGradientStop stop2 = gradFill.getGsLst().addNewGs();
//        stop2.setPos(100000);
//        stop2.addNewSrgbClr().setVal(new byte[]{(byte)0, (byte)0, (byte)139}); // 深蓝
//    }

    private void setSolidLightBlueBackground(XSLFSlide slide) {
        CTSlide ctSlide = slide.getXmlObject();
        CTCommonSlideData cSld = ctSlide.getCSld();

        CTBackground bg = cSld.isSetBg() ? cSld.getBg() : cSld.addNewBg();
        CTBackgroundProperties bgPr = bg.isSetBgPr() ? bg.getBgPr() : bg.addNewBgPr();

        CTSRgbColor srgbColor = bgPr.addNewSolidFill().addNewSrgbClr();
        srgbColor.setVal(new byte[]{(byte)173, (byte)216, (byte)230}); // #ADD8E6 浅蓝色
    }

    @GetMapping("/pptdownload/{fileName}")
    public void pptdownloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            String fullPath = System.getProperty("java.io.tmpdir") + File.separator + fileName;
            File file = new File(fullPath);

            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation");

            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {

                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("Error downloading document");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


}
